package com.tensquare.user.controller;

import cn.hutool.core.util.StrUtil;
import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private HttpServletRequest request;
    //1.发送验证码
    @PostMapping("sendsms/{mobile}")
    public Result sendsms(@PathVariable String mobile){
        userService.sendsms(mobile);
        return new Result(true, StatusCode.OK,"发送验证码成功");
    }
    //2.注册用户
    @PostMapping("register/{code}")
    public Result register(@PathVariable String code,@RequestBody User user){
        //1.判断验证码
        //if (userService.isCode(user.getMobile(),code)){
        userService.save(user);
        return new Result(true,StatusCode.OK,"注册用户成功");
//        }else {
//            return new Result(false,StatusCode.ERROR,"验证码输入有误,请重新输入");
//        }
    }
    //3.用户登录
    @PostMapping("login")
    public Result login(@RequestBody User user){
        User loginUser=userService.isTrue(user);
        if (loginUser!=null){
            String token = jwtUtils.getToken(loginUser.getId(), loginUser.getNickname(), "user");
            return new Result(true,StatusCode.OK,"用户登录成功!",token);
        }
        return new Result(false,StatusCode.LOGINERROR,"用户名或密码有误");
    }
    //4.删除用户
    @DeleteMapping("{userId}")
    public Result delete(@PathVariable String userId){
        Claims claims = (Claims) request.getAttribute("claims");
        System.out.println("claims = " + claims);
        if (claims!=null && "admin".equals(claims.get("roles"))){
            userService.delete(userId);
            return new Result(true,StatusCode.OK,"删除用户成功");
        }
        return new Result(false,StatusCode.ACCESSERROR,"权限不足");
    }
    //5.修改fans值
    @PutMapping("updateFans/{id}/{count}")
    public void updateFans(@PathVariable String id,@PathVariable int count){
        userService.updateFans(id,count);
    }
    //6.修改follow值
    @PutMapping("updateFollow/{id}/{count}")
    public void updateFollow(@PathVariable String id,@PathVariable int count){
        userService.updateFollow(id,count);
    }
}
